#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2011 OpenWrt.org
START=98

add_config_bool() {
	local section="$1"
	local option="$2"
	local value="$3"
	local default="$4"
	local _val

	config_get_bool _val "$section" "$option" "$default" [ "$_val" -gt 0 ] && _val="true" || _val="false" append args "$3 $_val" "\n" }

add_config() {
	local section="$1"
	local option="$2"
	local value="$3"
	local _val

	config_get _val "$section" "$option"
	[ -n "$_val" ] && append args "$3 $_val" "\n"
}

start_instance() {
	local cfg="$1"
	CFGFILE="/var/etc/aiccu-${cfg}.conf"
	PIDFILE="/var/run/aiccu-${cfg}.pid"
	args=""

	add_config "$cfg" username username
	add_config "$cfg" password password
	add_config "$cfg" server server
	add_config "$cfg" protocol protocol
	add_config "$cfg" interface ipv6_interface
	add_config "$cfg" tunnel_id tunnel_id
	add_config_bool "$cfg" requiretls requiretls 0
	add_config_bool "$cfg" defaultroute defaultroute 1
	add_config_bool "$cfg" nat behindnat 1
	add_config_bool "$cfg" heartbeat makebeats 1
	append args "daemonize true" "\n"
	append args "pidfile $PIDFILE" "\n"

	mkdir -p /var/run /var/etc
	echo -e "$args" > "$CFGFILE"

	config_get_bool enabled "$cfg" enabled '1'
	[ "$enabled" -gt 0 ] && aiccu start "$CFGFILE" &
}

stop_instance() {
	local cfg="$1"
	aiccu stop "/var/etc/aiccu-${cfg}.conf"
}

restart_instance() {
	local cfg="$1"
	config_get_bool restart "$cfg" restart 0
	[ "$restart" -eq 1 ] && stop_instance "$cfg"
	start_instance "$cfg"
}

start() {
	config_load aiccu
	config_foreach start_instance aiccu
}

stop() { 
	config_load aiccu
	config_foreach stop_instance aiccu
}

restart() {
	config_load aiccu
	config_foreach restart_instance aiccu
}